<?php namespace App\Http\Controllers\Api;

use App\Exceptions\FileUploadException;
use App\Exceptions\NotFoundException;
use App\Files;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Symfony\Component\HttpFoundation\File;
use App\Services\FileManager;

class FileController extends ApiController
{
    public function uploadFile(Guard $guard,Request $request){
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $uploadFile = $request->file('file');

        if(!$request->hasFile('file')){
            throw new FileUploadException(FileUploadException::UploadFail);
        }

        if(!$uploadFile->isValid()){
            throw new FileUploadException(FileUploadException::UploadFailWithError,['error'=>$uploadFile->getErrorMessage()]);
        }

        $fileName = $uploadFile->getClientOriginalName();

        $fileModel = FileManager::UploadFile($uploadFile,$fileName);

        Session::put('FileId',$fileModel->id);

        return $this->buildResponse(trans('api.bp_upload.success'),$fileModel);
    }

    public function getFileAsDownloadById($id = 0){

        /** @var Files $files */
        $files = Files::find($id);

        if($id == 0 || !$files)
            throw new NotFoundException(NotFoundException::FileNotFound);

        return \Response::download($files->getLocalPath(),urldecode($files->file_name),[],'inline');
    }
}